<template>
  <view>
    <up-card
      v-for="(item, index) in addressList" :key="index"
    >
      <template #head>
        <up-row justify="space-between">
          <view @tap="toAddrMng(item)">{{ item.name }}</view>
          <up-row v-if="type == 'edit'">
            <up-switch v-model="item.isDefault" @change="checkBtn(item)" :size="18"></up-switch>
            <view class="u-p-l-10">是否默认</view>
          </up-row>
          <up-row v-else>
            <view class="u-p-l-10" v-if="item.isDefault">默认收货地址</view>
          </up-row>
        </up-row>
      </template>
      <template #body>
          <view class="" slot="body" @tap="toAddrMng(item)">
              <view class="u-flex u-border-bottom u-p-t-0 u-p-b-10">
                <view class="u-body-item-title u-line-2">{{ item.phone }}</view>
              </view>
              <view class="u-flex u-p-t-10">
                <view class="u-body-item-title u-line-2">{{ item.address }}</view>
                <view class="u-body-item-title u-line-2">{{ item.num }}</view>
              </view>
          </view>
      </template>
	</up-card>

    <up-empty
      mode="address"
      v-if="addressList.length == 0"
      style="margin-top: 50px;"
    >
    </up-empty>

    <view class="footer u-p-20">
      <up-button :color="$u.color.mainColor" text="新增" @tap="toAddrMng(null)"></up-button>
    </view>
  </view>
</template>

<script>
import { useAddrStore } from '@/stores/addr'
export default {
  data() {
    return {
      addressList: [],
      eventChannel: null,
      type: 'edit',
      addrStore: useAddrStore()
    };
  },
  onLoad(options) {
    this.type = options.type || 'edit'

    const eventChannel = this.getOpenerEventChannel();
    this.eventChannel = eventChannel;

    this.init()
  },
  onShow() {
    this.init()
  },
  methods: {
    async init() {
      let {data} = await this.$api.user.address()
      this.addressList = data || []
    },
    toAddrMng(row) {
      if (this.type == 'select' && row) {
        this.eventChannel.emit('addListenerSendAddr', row);
        uni.navigateBack({});
      } else {
        this.addrStore.setData(row)
        uni.navigateTo({
          url: '/pages/address/manage'
        })
      }
    },
    async checkBtn(item) {
      let data = await this.$api.user.addressSetDefualt({
        id: item.id,
        isDefault: item.isDefault
      })
      if (data.code == 200) {
        this.init()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  width: calc(100% - 20px);
  height: auto;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 999;
}
</style>